//
//  ClubSquareViewController.swift
//  77Club
//
//  Created by Apple on 2024/8/26.
//

import UIKit
import ZLPhotoBrowser
import JXSegmentedView

class ClubDynamicViewController: ClubBaseViewController, RaeAnimationProtocol {

    private var releaseButton = c_make_ex(UIButton.self)
        .image("Square_add").end()
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ClubDynamicListCell.self)
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 306.0.Scale
        return tableView
    }()
    
    private var dataSource = [ClubGameCircleModel]()
    private var pageIndex = 1
    private var playingIndexPath: IndexPath?
    private var currentVC = true
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        releaseButton.isHidden = false
        currentVC = true
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        releaseButton.isHidden = true
        currentVC = false
        NotificationCenter.default.post(name: .stopDynamicAudioPlayer, object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        loadData()
        
        view.subviews{
            tableView
        }
        
        tableView.fillContainer()
        
        releaseButton.addTarget(self, action: #selector(clickAddButton), for: .touchUpInside)
        self.view.addSubview(releaseButton)
        let panGesture = UIPanGestureRecognizer(target: self, action:#selector(dragAction(gesture:)))
        releaseButton.addGestureRecognizer(panGesture)
        releaseButton.snp.makeConstraints { make in
            make.right.equalTo(0)
            make.width.equalTo(88.0.Scale)
            make.height.equalTo(88.0.Scale)
            make.bottom.equalTo(-CGFloat.tabBar_height)
        }
        tableView.refresh_loadMore {
            self.loadMoreData()
        }.refresh_pull {
            self.loadNewData()
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(updateNewData), name: .updateDynamicListData, object: nil)
    }
    
}

//MARK: - UITableViewDelegate, UITableViewDataSource
extension ClubDynamicViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return self.dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        //动态
        let cell = tableView.dequeueReusableCell(withIdentifier: "ClubDynamicListCell", for: indexPath) as! ClubDynamicListCell
        cell.circleModel = self.dataSource[indexPath.row]
        cell.jumpToDetail = { id in
            let detailController = ClubDynamicDetailViewController()
            detailController.dynamicID = id
            self.navigationController?.pushViewController(detailController, animated: true)
        }
        cell.didSelectImage = { index,images in
            self.selectImage(index: index, images: images)
        }
        cell.didSelectVideo = { url in
            self.selectVideo(url: url)
        }
        cell.toGameDetailVC = { gid in
            let detailVC = ClubGameDetailViewController()
            detailVC.gameId = gid
            self.navigationController?.pushViewController(detailVC, animated: true)
        }
        cell.toTopicDetailVC = { topicId in
            let detailVC = ClubTopicDetailViewController()
            detailVC.topicId = topicId
            self.navigationController?.pushViewController(detailVC, animated: true)
        }
        cell.showMoreView = { md in
            let moreView = ClubMoreView()
            moreView.uid_des = md.uid_des
            moreView.reportBlock = {
                if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
                    let reportVC = ClubReportViewController()
                    reportVC.dynamicID = md.id
                    reportVC.updateDataBlock = {
                        self.loadNewData()
                    }
                    self.present(reportVC, animated: true)
                }else{
                    self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
                }                
            }
            moreView.delBlock = {
                Task{
                    let res = await self.network.request(.delDynamic(id: md.id))
                    if res.isSuccess {
                        "删除成功".toast_success
                        self.loadNewData()
                    }
                }
            }
            moreView.copyShareBlock = { type in
                self.shareDetail(type: type, shareUrl: md.share_url)
            }
            self.entryAnimate.animation(show: moreView)
        }
        cell.otherUserInfoVC = { uid in
            if uid.count > 0 {
                if let user_id = UserDefaultsManager.getString(forKey: .uid), user_id.count > 0, user_id == uid {
                    let otherVC = ClubMineInfoViewController()
                    self.navigationController?.pushViewController(otherVC, animated: true)
                }else{
                    let otherVC = ClubOtherInfoViewController()
                    otherVC.uid = uid
                    otherVC.updateBlock = {
                        self.loadNewData()
                    }
                    self.navigationController?.pushViewController(otherVC, animated: true)
                }
            }                        
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let detailController = ClubDynamicDetailViewController()
        detailController.dynamicID = dataSource[indexPath.row].id
        detailController.updateDataBlock = {
            self.loadNewData()
        }
        self.navigationController?.pushViewController(detailController, animated: true)
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        guard let visibleCells = tableView.visibleCells as? [ClubDynamicListCell] else { return }
            
        // 获取 TableView 的中心位置
        let tableViewCenter = tableView.bounds.size.height / 2 + tableView.contentOffset.y

        for cell in visibleCells {
            guard let indexPath = tableView.indexPath(for: cell) else { continue }
            let cellCenterY = cell.center.y

            // 判断 Cell 中心是否接近 TableView 中心
            if tableView.contentOffset.y == 0 {
                loadFirstVideo()
            }
            if abs(cellCenterY - tableViewCenter) < 50 { // 设定 50 为接近程度的阈值
                if playingIndexPath != indexPath {
                    playingIndexPath = indexPath
                    cell.playVideo()  // 播放视频
                }
            } else {
                if playingIndexPath == indexPath {
                    cell.pauseVideo()  // 暂停视频
                    playingIndexPath = nil
                }
            }
        }
    }
}


//MARK: action
extension ClubDynamicViewController {
    
    private func selectImage(index: Int, images: [String]) {
        
        var datas: [Any] = []
        for a in images {
            datas.append(URL(string: a)!)
        }
        let vc = ZLImagePreviewController(datas: datas, index: index, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .image
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
    
    private func selectVideo(url: String) {
        
        let vc = ZLImagePreviewController(datas: [URL(string: url)!], index: 0, showSelectBtn: false,showBottomView: false) { (url) -> ZLURLType in
            
            return .video
        } urlImageLoader: { (url, imageView, progress, loadFinish) in
            imageView.kf.setImage(with: url) { (receivedSize, totalSize) in
                let percentage = (CGFloat(receivedSize) / CGFloat(totalSize))
                debugPrint("\(percentage)")
                progress(percentage)
            } completionHandler: { (_) in
                loadFinish()
            }
        }
        
        vc.doneBlock = { (datas) in
            debugPrint(datas)
        }
        
        vc.modalPresentationStyle = .fullScreen
        self.showDetailViewController(vc, sender: nil)
    }
    
    @objc private func dragAction(gesture: UIPanGestureRecognizer) {
        
        // 移动状态
        let moveState = gesture.state
        switch moveState {
        case .began:
            break
        case .changed:
            // floatBtn 获取移动轨迹
            let point = gesture.translation(in: self.view)
            self.releaseButton.center = CGPoint(x: self.releaseButton.center.x + point.x, y: self.releaseButton.center.y + point.y)
            break
        case .ended:
            // floatBtn 移动结束吸边
            let point = gesture.translation(in: self.view)
            var newPoint = CGPoint(x: self.releaseButton.center.x +  point.x, y: self.releaseButton.center.y + point.y)
            if newPoint.x < .screenWidth / 2.0 {
                newPoint.x = self.releaseButton.bounds.width/2 + 17.0.Scale
            } else {
                newPoint.x = .screenWidth - self.releaseButton.bounds.width/2 - 17.0.Scale
            }
            if newPoint.y <= self.releaseButton.bounds.height/2 + 17.0.Scale + .navi_height{
                newPoint.y = self.releaseButton.bounds.height/2 + 17.0.Scale + .navi_height
            } else if newPoint.y >= self.view.bounds.height - self.releaseButton.bounds.height/2 - 17.0.Scale {
                newPoint.y = self.view.bounds.height - self.releaseButton.bounds.height/2 - 17.0.Scale
            }
            // 0.5秒 吸边动画
            UIView.animate(withDuration: 0.5) {
                self.releaseButton.center = newPoint
            }
            break
        default:
            break
        }
        // 重置 panGesture
        gesture.setTranslation(.zero, in: self.view)
    }
    
    @objc private func clickAddButton() {

        if let uid = UserDefaultsManager.getString(forKey: .uid), uid.count > 0 {
            let pushVC = ClubPushDynamicViewController()
            pushVC.updateData = {
                self.loadNewData()
            }
            self.present(pushVC, animated: true)
        }else{
            self.navigationController?.pushViewController(ClubLoginViewController(), animated: true)
        }
    }
    
    private func shareDetail(type: Int, shareUrl: String) {
        if type == 3 {
            ClubGlobalTool.shared.shareToQQ(title: ClubGlobalTool.shared.dynamicShareTitle, description: ClubGlobalTool.shared.dynamicShareDes, imageUrl: "https://www.77.top/static/ios_logo.jpg", url: shareUrl)
        }else if type == 4 {
            "分享口令已复制成功".toast_success
            UIPasteboard.general.string = shareUrl
        }else{
            ClubGlobalTool.shared.shareToWechat(title: ClubGlobalTool.shared.dynamicShareTitle, des: ClubGlobalTool.shared.dynamicShareDes, image: "AppIcon".toImage!, shareUrl: shareUrl, shareType: type)
        }
    }
    
    private func loadFirstVideo(){
        
        if currentVC {
            let md = self.dataSource[0]
            if md.video.count > 0 {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    let indexPath = IndexPath(row: 0, section: 0)
                    self.playingIndexPath = indexPath
                    let cell = self.tableView.cellForRow(at: indexPath) as! ClubDynamicListCell
                    cell.playVideo()  // 播放视频
                }
            }
        }        
    }
}

//MARK: data
extension ClubDynamicViewController {
    
    func loadData() {

        Task {
            let models = await network.request(.dynamicList(page: pageIndex),type: ClubGameCircleModel.self)
            tableView.refresh_end()
            self.dataSource.removeAll()
            if models.isSuccess, let models = models.models {
                if models.count > 0 {
                    for md in models {
                        var mod = md
                        var itemSize: CGSize = .zero
                        if md.video.count > 0 {
                            itemSize = .zero
                        }else if md.img.count == 1 {
                            itemSize = CGSize (width: CGFloat.screenWidth - 104.0.Scale, height: 152.0.Scale)
                        }else if md.img.count == 2 {
                            itemSize = CGSize (width: (CGFloat.screenWidth - 106.0.Scale)/2.0, height: 83.0.Scale)
                        }else if md.img.count > 2 {
                            let w = (CGFloat.screenWidth - 110.0.Scale)/3
                            itemSize = CGSize (width: w, height: w)
                        }else{
                            itemSize = .zero
                        }
                        mod.itemSize = itemSize
                        self.dataSource.append(mod)
                    }
                }
                self.tableView.reloadData()
                self.loadFirstVideo()
            }
        }
    }
    
    @objc func loadNewData() -> () {
        pageIndex = 1
        loadData()
    }
    
    @objc func loadMoreData() -> () {
        pageIndex += 1
        Task {
            let models = await network.request(.dynamicList(page: pageIndex),type: ClubGameCircleModel.self)
            if models.isSuccess, let models = models.models {
                if models.count > 0 {
//                    self.dataSource.append(contentsOf: models)
                    for md in models {
                        var mod = md
                        var itemSize: CGSize = .zero
                        if md.video.count > 0 {
                            itemSize = .zero
                        }else if md.img.count == 1 {
                            itemSize = CGSize (width: CGFloat.screenWidth - 104.0.Scale, height: 152.0.Scale)
                        }else if md.img.count == 2 {
                            itemSize = CGSize (width: (CGFloat.screenWidth - 106.0.Scale)/2.0, height: 83.0.Scale)
                        }else if md.img.count > 2 {
                            let w = (CGFloat.screenWidth - 110.0.Scale)/3
                            itemSize = CGSize (width: w, height: w)
                        }else{
                            itemSize = .zero
                        }
                        mod.itemSize = itemSize
                        self.dataSource.append(mod)
                    }
                }else{
                    tableView.refresh_end(true)
                }
                self.tableView.reloadData()
            }
        }
    }
    
    @objc private func updateNewData(){
        loadNewData()
    }
}

extension ClubDynamicViewController:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}
